import {createContext, useReducer,useContext} from "react"

const PartContext = createContext()

export const usePartContext = () => useContext(PartContext)

const partState = {
    goods:[],
    colGoods:[]
}

const PartReducer = (state,action)=>{
    switch(action.type) {
        case "getGoods":
            return {...state,goods:action.goods}
        case "collect":
            return {
                ...state,
                goods:state.goods.filter(item=>{
                    if(item.id===action.id){        
                        item.isCollect=true
                    }
                    return item;
                }),
                colGoods:[
                    action.good,
                    ...state.colGoods,
                ]
            }
        case "cancel":
            return{
                ...state,
                colGoods:state.colGoods.filter(item=>item.id!==action.id),
                goods:state.goods.filter(item=>{
                    if(item.id===action.id){
                        item.isCollect=false
                    }
                    return item;
                })
            }
        default:
            return state;
    }
}

const PartProvider = ({children})=>{
    const [state,dispatch] = useReducer(PartReducer,partState);
    return (
        <PartContext.Provider
            value={
                {state,dispatch}
            }
        >
            {children}
        </PartContext.Provider>
    )
}

export default PartProvider;